package cn.com.infohold.smartcity.parent;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.View;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import cn.com.infohold.smartcity.R;
import cn.com.infohold.smartcity.data.XmlData;
import cn.com.infohold.smartcity.jpush.JpushExtra;
import cn.pedant.SweetAlert.SweetAlertDialog;
import common.base.BaseActivity;
import common.utils.Tips;
import common.utils.ViewUtils;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import library.http.Http;
import library.permission.PermissionsManager;
import library.utils.Utils;
import library.utils.bar.SystemBar;

/**
 * Created by Mr.Fan on 2016-4-6.
 */
public abstract class ParentActivity extends BaseActivity {
    private static final CompositeDisposable disposables = new CompositeDisposable();

    private static final int BAR_COLOR_ID = R.color.colorPrimary;
    private static final int BAR_ALPHA = 0xFF / 1;
    //public static final String USER_ID = XmlData.getInstance().getUserInfo().getId();

    SweetAlertDialog mDialogForceLogout;

    public void overridePendingTransitionFade() {
        overridePendingTransition(R.anim.abc_fade_in, R.anim.abc_fade_out);
    }

    public void addSubscribe(Disposable disposable) {
        if (disposable != null) {
            disposables.add(disposable);
        }
    }

    protected abstract Object inflateView();

    protected abstract void initView(View anchor);

    protected boolean enableNavigationBar() {
        return false;
    }

    protected boolean isShowStatusBarShadow() {
        return false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addActivity();

        Object obj = inflateView();
        if (obj instanceof Integer)
            setContentView(Integer.parseInt(obj.toString()));
        else if (obj instanceof View)
            setContentView((View) obj);

        ViewUtils.inject(this, getWindow().getDecorView());

        initView(getWindow().getDecorView());
        EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onJpushExtra(JpushExtra jpushExtra) {
        if (jpushExtra == null)
            return;
        if (jpushExtra.getType() == 5) {
            forceLogout();
        }
    }

    private boolean isInMainFunction() {
        Class cls = getClass();
//        if (!cls.equals(LauncherActivity.class) &&
//                !cls.equals(LoginActivity.class)) {
//            return true;
//        }
        return false;
    }

    public void forceLogout() {
        if (!Utils.isTopActivity(this) && !isInMainFunction() && mDialogForceLogout != null)
            return;
        if (Utils.isDebuggable(getApplicationContext())) {
            Tips.obtain(getActivity()).warn("您的账号已在其他设备登录");
            return;
        }
        mDialogForceLogout = new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
                .setTitleText("您的账号已在其他设备登录")
                .setContentText("")
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        sDialog.dismissWithAnimation();
                    }
                });
        if (!Utils.isDebuggable(getApplicationContext())) {
            mDialogForceLogout.setCancelable(false);
            mDialogForceLogout.setCanceledOnTouchOutside(false);
        }
        mDialogForceLogout.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                mDialogForceLogout = null;
//                Utils.startActivity(
//                        getApplicationContext(),
//                        LoginActivity.class,
//                        Intent.FLAG_ACTIVITY_CLEAR_TASK);
            }
        });
        mDialogForceLogout.show();
    }

    @Override
    public void finish() {
        Http.cancel(this);
        super.finish();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        Http.cancel(this);
        disposables.clear();
        super.onDestroy();
        removeActivity();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionsManager.getInstance().notifyPermissionsChange(permissions, grantResults);
    }

    public ParentActivity getActivity() {
        return this;
    }

    protected final void setSystemBar() {
        setSystemBarColorByResource(BAR_COLOR_ID);
    }

    public final void setSystemBarTransparent() {
        if (enableNavigationBar()) {
            SystemBar.obtain()
                    .statusBar().transparent().shadow(isShowStatusBarShadow())
                    .navigationBar().transparent()
                    .apply(this);
        } else {
            SystemBar.obtain()
                    .statusBar().transparent().shadow(isShowStatusBarShadow())
                    .apply(this);
        }
    }

    public final void setSystemBarTranslucent() {
        if (enableNavigationBar()) {
            SystemBar.obtain()
                    .statusBar().translucent().shadow(isShowStatusBarShadow())
                    .navigationBar()
                    .apply(this);
        } else {
            SystemBar.obtain()
                    .statusBar().translucent().shadow(isShowStatusBarShadow())
                    .apply(this);
        }
    }

    public final void setSystemBarColorByResource(int colorId) {
        setSystemBarColor(getResources().getColor(colorId));
    }

    public final void setSystemBarColor(int color) {
        if (enableNavigationBar()) {
            SystemBar.obtain()
                    .statusBar().color(color).alpha(BAR_ALPHA).shadow(isShowStatusBarShadow())
                    .navigationBar()
                    .apply(getWindow());
        } else {
            SystemBar.obtain()
                    .statusBar().color(color).alpha(BAR_ALPHA).shadow(isShowStatusBarShadow())
                    .apply(getWindow());
        }
    }

    public void setSystemBarForMultiLayout(View main) {
        setSystemBarColorForMultiLayout(main, getResources().getColor(BAR_COLOR_ID));
    }

    public void setSystemBarColorForMultiLayout(View main, int color) {
        if (enableNavigationBar()) {
            SystemBar.obtain()
                    .setContentViewForMultiLayout(main)
                    .statusBar().color(color).alpha(BAR_ALPHA).shadow(isShowStatusBarShadow())
                    .navigationBar()
                    .apply(getWindow());
        } else {
            SystemBar.obtain()
                    .setContentViewForMultiLayout(main)
                    .statusBar().color(color).alpha(BAR_ALPHA).shadow(isShowStatusBarShadow())
                    .apply(getWindow());
        }
    }

    @Override
    protected boolean hideKeyBoardAuto() {
        return true;
    }

    @Override
    public void onBackPressed() {
        if (onFragmentBackPressed()) {

        } else {
//            moveTaskToBack(true);
            super.onBackPressed();
        }
    }

    protected boolean onFragmentBackPressed() {
        return onFragmentBackPressed(getSupportFragmentManager());
    }

    private boolean onFragmentBackPressed(FragmentManager fragmentManager) {
        List<Fragment> list = fragmentManager.getFragments();
        if (list != null && list.size() > 0)
            for (Fragment fragment : list) {
                if (fragment instanceof ParentFragment && !fragment.isHidden()) {
                    if (onFragmentBackPressed(fragment.getChildFragmentManager())) {
                        return true;
                    } else if (((ParentFragment) fragment).onBackPressed()) {
                        return true;
                    }
                }
            }
        return false;
    }


    private static final Map<String, WeakReference<ParentActivity>> list =
            Collections.synchronizedMap(new LinkedHashMap<String, WeakReference<ParentActivity>>());

    public void addActivity() {
        synchronized (list) {
            list.put(String.valueOf(this), new WeakReference<>(this));
        }
    }

    public void removeActivity() {
        synchronized (list) {
            list.remove(String.valueOf(this));
        }
    }

    public static void finishAllActivities() {
        synchronized (list) {
            Iterator it = list.keySet().iterator();
            while (it.hasNext()) {
                Object key = it.next();
                WeakReference<ParentActivity> ref = list.get(key);
                if (ref != null) {
                    ParentActivity act = ref.get();
                    if (act != null) {
                        act.finish();
                    }
                }
            }
        }
    }

    public void finishOtherActivities() {
        synchronized (list) {
            Iterator it = list.keySet().iterator();
            while (it.hasNext()) {
                Object key = it.next();
                WeakReference<ParentActivity> ref = list.get(key);
                if (ref != null) {
                    ParentActivity act = ref.get();
                    if (act != null && !act.equals(this)) {
                        act.finish();
                    }
                }
            }
        }
    }


}
